<?php

require 'facebook.php';
require 'config.inc.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => $fbconfig['app_id'],
  'secret' => $fbconfig['secret_key'],
  'cookie' => true,
));

// We may or may not have this data based on a $_REQUEST or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid= $facebook->getUser();
    $me = $facebook->api('/me');
//    $access_token = $facebook->getAccessToken();
    $access_token = $session['access_token'];
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

// login or logout url will be needed depending on current user state.
if(!$session) {
  $loginUrl = $facebook->getLoginUrl(array('canvas'=>1,'fbconnect'=>0,'next'=>$fbconfig['appbase_url']));
  echo "<script type='text/javascript'> top.location.href='$loginUrl';</script>";
}
$p=$_REQUEST["p"];
if(!isset($p))
	$p="recent";
$o=$_REQUEST["o"];
if(!isset($o))
	$o=0;
if(is_null($o))
	$o=0;
$l=$_REQUEST["l"];
if(!isset($l))
	$l=0;
      
?>

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <title>LinkStar - Fun way to share links</title>
    <link rel="stylesheet" type="text/css" href="main.css" />
    <script language="javascript" src="main.js"> </script>
  </head>
  <body>
    <!--
      We use the JS SDK to provide a richer user experience. For more info,
      look here: http://github.com/facebook/connect-js
    -->
    <div id="fb-root"></div>
    <script>
	
		window.fbAsyncInit = function() {
        FB.init({
          appId   : '<?php echo $facebook->getAppId(); ?>',
          session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true, // parse XFBML
        });
        
       	// whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
        		window.location.reload();
        });
         FB.Event.subscribe('auth.logout', function() {
				$session = null;
				window.location.reload();
        });
        
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
      
     
    </script>
   <table id="template" align="left" width="750">
      	<tr valign="top">
      		<td class="left"> 
      			<img id="logo" src='images/linkstar2.png' /><br/> <font id="share-font">share and organize your links</font> 
      		</td>
      		
      		
      		<td class="right" valign="top"> 
      		
				<h2 id="greetme"> Hello User </h2>   		
				<!-- quick share -->
				<form method="post" action="javascript:addlink()"> 
					<input id="quickshare" type="text" name="link_added" value="Quickshare: Type or Paste URL" onFocus="if(value=='Quickshare: Type or Paste URL') value=''" onBlur="if(value=='') value='Quickshare: Type or Paste URL'"/>
					<input type="image" id="add_button" src="images/add.png" value="Add"/>
				</form>
      		
      		</td>
      	</tr>
      	<tr valign="top">
      		<td id="nav" class="left" align='left'>
      			<ul id="nav_list">
					<li class="non-selected" id="nav_recent" onclick="javascript:recent(0,4)"> LINKS </li>
					<li class="non-selected" id="nav_groups" onclick="javascript:groups(0,14)"> GROUPS  </li>
					<li class="non-selected" id="nav_friends" onclick="javascript:friends(0,12)"> FRIENDS </li>
					<li class="non-selected" id="nav_tags" onclick="javascript:tags()"> TAGS </li>
					<li class="non-selected" id="nav_status" onclick="javascript:status()"> PROFILE </li>
   				</ul>
   				<h4> Friends using Linkstar: </h4>
   				<fb:facepile width="160" max_rows="7" app_id="<?php echo $fbconfig['app_id']; ?>"></fb:facepile><br/>
   				<hr width="1"/>
   				<a class="normal" onclick="javascript:inviteToApp()" /> Invite Other Friends to Linkstar </a>
   				
   				<!-- <a href="javascript:stream()"> click </a> -->
   				
       		</td>
      		<td id="info" class="right">
   
   				<div id="heading"></div>
				<div id="tabs-area">
				
				</div>
				<div id="data">


				</div>
   
      		</td>
        <tr>
      	</tr>
      </table>
      <div id="invite"> </div>
      <script>
     
      //execute as soon as DOM is loaded
   	window.onDomReady = DomReady;
   	
   	//Setup the event
   	function DomReady(fn)
   	{
   		//W3C
   		if(document.addEventListener)
   		{
   			document.addEventListener("DOMContentLoaded", fn, false);
   		}
   		//IE
   		else
   		{
   			document.onreadystatechange = function(){readyState(fn)}
   		}
   	}
   	
   	//IE execute function
   	function readyState(fn)
   	{
   		//dom is ready for interaction
   		if(document.readyState == "interactive")
   		{
   			fn();
   		}
   	}
   	window.onDomReady(onReady);
   	
   	//do on ready
   	function onReady()
   	{
		document.getElementById('greetme').innerHTML='Hello <fb:name uid="loggedinuser" use-you="false" linked="false"></fb:name>';
		<?php
				//$uid = 1234;
				//$access_token = "abcd";

				$con = mysql_connect("localhost", "vatsav", "2T*vzcd");
				if (!$con)
				{
				  die('Could not connect: ' . mysql_error());
				}

				$db_selected = mysql_select_db("vatsav", $con);
					if (!$db_selected) {
						die ('Cant use db : ' . mysql_error());
				}

				//$result = mysql_query("SELECT * FROM users where uid=".$_POST['uid']);	
				$result = mysql_query("SELECT * FROM users where uid=".$uid);	
				// Check result
				if (!$result) {
				   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
				   die($message);
				}

				if($row = mysql_fetch_row($result))
				{
					$result = mysql_query("update users set access_token='".$access_token."' where uid=".$uid);
				}
				else //if($row['access_token'] != $access_token)
				{
					$result = mysql_query("insert into users values(".$uid.",'".$access_token."')");
					//  mysql_query("insert into users values(".$_POST['uid'].",'".$_POST['access_token']."')");;
					echo "(function(){location.href='http://studentweb.comminfo.rutgers.edu/2010-9-673-01/vatsav/intro.html';})();";
				}

				if (!$result) {
				   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
				   die($message);
				}
				
				$result = mysql_query("SELECT friendid FROM invitations where friendid=".$uid);	
				// Check result
				if (!$result) {
				   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
				   die($message);
				}

				if($row = mysql_fetch_row($result))
				{
					$p="invitations";
				}

				mysql_close($con);

			?>
   		profile(<?php echo $uid; ?>,<?php echo "'".$access_token."'"; ?>,<?php echo "'".$p."'"; ?>,<?php echo $o; ?>,<?php echo $l; ?>);
   	}
   	
   	function stream()
	   		{
				var publish = {
			  method: 'stream.publish',
			  message: 'A fun app',
			  attachment: {
			    name: 'Linkstar',
			    caption: 'An easy way to share and organize your links',
			    description: (
			      'Linkstar is an application that allows you to categorize and share links with your friends in Facebook'
			    ),
			    href: 'http://apps.facebook.com/linkstar/',
			    media: [
			      {
			        type: 'image',
			        href: 'http://apps.facebook.com/linkstar',
			        src: 'http://studentweb.comminfo.rutgers.edu/2010-9-673-01/vatsav/images/linkstar2.png'
			      }
			    ]
			  },
			  action_links: [
			    { text: 'Linkstar', href: 'http://apps.facebook.com/linkstar/' }
			  ],
			  user_message_prompt: 'Share your thoughts about Linkstar'
			};
			
				FB.ui(publish);
		}
  
   </script>
   
  </body>
</html>